package com.quintal.androidtouchcloud.mainActivities;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Account;
import com.dropbox.client2.DropboxAPI.DropboxLink;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.quintal.androidtouchcloud.R;
import com.quintal.androidtouchcloud.nfc.NFCReader;
import com.quintal.androidtouchcloud.nfc.NFCWriter;
import com.quintal.androidtouchcloud.storage.DBManager;
//import android.annotation.SuppressLint;

public class MainActivity extends Activity {

	final static private String MODULE = "TouchCloud MainActivity";

	final static private String USER_KEY = "user";
	final static private String EMAIL_KEY = "email";
	final static private String USER_ID_KEY = "user_id";
	final static private String SHARE_LINK_KEY = "share_link";
	final static private String INSERTED_KEY = "is_inserted";
	final static private String TAG_KEY = "nfc_id";
	final static private String PRIVACY_KEY = "privacy";
	final static private String APP_KEY = "26oq4i0h4zsd19o";
	final static private String APP_SECRET = "21grqqryfaqdafd";
	final static private String ACCOUNT_PREFS_NAME = "prefs";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
	private DropboxAPI<AndroidAuthSession> mDBApi;
	private boolean _fromDropbox=false;
	private final GUI_Handler gui_handler = new GUI_Handler();
	private ProgressDialog mDialog;
	AccessTokenPair tokens;
	private Button _manageLinks;

	private Intent intent;
	private Bundle extras;
	private String action;
	
	public static Intent openFileIntent;
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayShowTitleEnabled(false);
		getActionBar().hide();
		setContentView(R.layout.activity_main);

		intent = getIntent();
		extras = intent.getExtras();
		action = intent.getAction();

		// Need to create database if it doesn't exist yet
		if (! DBManager.databaseExists())
			DBManager.initDatabase();
		else
			Log.i(MODULE, "Database already exists!!");

		File SDCardRoot = Environment.getExternalStorageDirectory();
		File file = new File(SDCardRoot+"/touchCloud/temp_files/");  // folder to store the temp files
		file.mkdir();

		AndroidAuthSession session = buildSession();
		mDBApi = new DropboxAPI<AndroidAuthSession>(session);
		if(!mDBApi.getSession().isLinked()){
			//Log.i(MODULE, " no dropbox linked.. starting process");
			mDBApi.getSession().startAuthentication(MainActivity.this);
		}
		else{
			if(isNewUser()){
				GatherUserInfo test = new GatherUserInfo();
				test.execute();
			}else{
				SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
				((TextView)findViewById(R.id.user_id_info)).setText("Hi "+prefs.getString(USER_KEY, ""));
			}
		}
		
	}
	//	
	@Override 
	public void onResume(){
		super.onResume();
		Log.e(MODULE, "is reader running "+isActivityRunning());
		if(isActivityRunning()){
			Intent i = new Intent(getApplicationContext(), NFCReader.class);
			startActivity(i);
			finish();
		}
		else if (action!=null && Intent.ACTION_SEND.equals(action)) {
					_fromDropbox = true;
					String shareLink = extras.getString("android.intent.extra.TEXT");// Get resource path
					//Log.i(MODULE, shareLink);
					Intent i = new Intent(getApplicationContext(), NFCWriter.class);
					i.putExtra(SHARE_LINK_KEY, shareLink);
					startActivityForResult(i, 0);
					finish();
				}
		else{
			if (mDBApi.getSession().authenticationSuccessful()) {
				try {
					// Required to complete auth, sets the access token on the session
					mDBApi.getSession().finishAuthentication();
					tokens = mDBApi.getSession().getAccessTokenPair();
					storeKeys(tokens.key, tokens.secret);
				} catch (IllegalStateException e) {
					//Log.e("DbAuth//Log", "Error authenticating", e);
				}
			}
			if(isNewUser()){
				GatherUserInfo test = new GatherUserInfo();
				test.execute();
			}else{
				SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
				TextView textView = (TextView) findViewById(R.id.app_description);
				SpannableString content = new SpannableString(getString(R.string.start_message));
				content.setSpan(new UnderlineSpan(), 58, 63, 0);
				textView.setText(content);
				((TextView)findViewById(R.id.user_id_info)).setText(getString(R.string.hi)+" "+prefs.getString(USER_KEY, "")+"!");
			}
			initView();
			updateCountViews();
			initDPButton();
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		if (requestCode == 1) {
			if(resultCode == RESULT_OK){
				this.onStop();
			}
			if (resultCode == RESULT_CANCELED) {
				//Write your code if there's no result
			}
		}
	}
	@Override
	public void onStop(){
		super.onStop();
	//	if(_fromDropbox) // if the app was open through the share command on dropbox we want to destroy it once the share starts.
		//	finish();
	}
	public boolean isActivityRunning() { 
		return NFCReader.isRunning();
	}
	private void initView(){
		_manageLinks = (Button)findViewById(R.id.manage_share_btn);
		_manageLinks.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch(event.getAction()){
				case MotionEvent.ACTION_DOWN:
					v.setBackgroundResource(R.drawable.button_background_pressed);
					((TextView)v).setTextColor(Color.parseColor("#FF0000"));
					break;
				case MotionEvent.ACTION_UP:
					v.setBackgroundResource(R.drawable.button_background);
					((TextView)v).setTextColor(Color.parseColor("#FFFFFF"));
					Uri uriUrl = Uri.parse("https://www.dropbox.com/links");
					Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
					startActivity(launchBrowser);
					break;
				}
				return true;
			}
		});
	}
	private void initDPButton(){
		Button DPButton = (Button)findViewById(R.id.openDP);
		DPButton.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				switch (arg1.getAction()){
				case MotionEvent.ACTION_DOWN:
					arg0.setBackgroundColor(Color.parseColor("#247AE0"));

					break;

				case MotionEvent.ACTION_UP:
					arg0.setBackgroundColor(Color.TRANSPARENT);
					goToDropbox();
					break;
				}
				return true;
			}
		});
	}
	private void goToDropbox(){
		try{
			Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.dropbox.android");
			startActivity(LaunchIntent);
		}catch(Exception e){
			finish();
		}
	}
	private void updateCountViews(){
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		int user_id = Integer.parseInt(prefs.getString(USER_ID_KEY, "0"));
		int[] count_tags = DBManager.getDBManager().countTags(user_id);
		((TextView)findViewById(R.id.tags_created)).setText(count_tags[0]+"");
		((TextView)findViewById(R.id.tags_read)).setText(count_tags[1]+"");
		//Log.e(MODULE, "got tags count");
	}
	private boolean isNewUser(){
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		return !prefs.getBoolean(INSERTED_KEY, false);
	}
	private String[] getKeys() {
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(ACCESS_KEY_NAME, null);
		String secret = prefs.getString(ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[2];
			ret[0] = key;
			ret[1] = secret;
			return ret;
		} else {
			return null;
		}
	}
	private void storeKeys(String key, String secret) {
		// Save the access key for later
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(ACCESS_KEY_NAME, key);
		edit.putString(ACCESS_SECRET_NAME, secret);
		edit.commit();
	}
	private AndroidAuthSession buildSession() {
		AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
		AndroidAuthSession session;
		String[] stored = getKeys();
		if (stored != null) {
			AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
		} else {
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
		}
		return session;
	}
	private void testGatherLink(String path){
		try {
			DropboxLink response;
			response = mDBApi.share(path);
			//Log.i("teste", "share link created "+response.url);
		} catch (DropboxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void storeUserInfo(String name,String id,String email){
		//Log.e(MODULE, "storing user data");
		((TextView)findViewById(R.id.user_id_info)).setText(getString(R.string.hi)+" "+name+"!");
		TextView textView = (TextView) findViewById(R.id.app_description);
		SpannableString content = new SpannableString(getString(R.string.start_message));
		content.setSpan(new UnderlineSpan(), 66, 71, 0);
		textView.setText(content);
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(USER_KEY, name);
		edit.putString(USER_ID_KEY, id);
		edit.putString(EMAIL_KEY, email);
		edit.commit();
	}
	public void handleWriteNfc(View v){
		Intent i = new Intent(getApplicationContext(),NFCWriter.class); 
		startActivity(i);
	}
	public void handleReadNfc(View v){
		Intent i = new Intent(getApplicationContext(),NFCReader.class); 
		startActivity(i);
	}
	public void handleDropBoxClick(View v){
		v.setBackgroundColor(Color.parseColor("#247AE0"));
		Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.dropbox.android");
		startActivity(LaunchIntent);
		this.finish();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void handleManageSharesClick(View v){
		if(v.getId()==R.id.manage_share_btn){
			Uri uriUrl = Uri.parse("https://www.dropbox.com/links");
			Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
			startActivity(launchBrowser);
		}
	}

	private String buildDownloadLink(String path){
		String url = path.replace("www.dropbox.com", "dl.dropboxusercontent.com");
		String keys[] =  getKeys();
		return url;
	}

	private void doDownloadFileDummy(String name, String path){
		try {

			URL http_url = new URL(buildDownloadLink(path));
			HttpURLConnection urlConnection = (HttpURLConnection) http_url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			//and connect!
			urlConnection.connect();
			File SDCardRoot = Environment.getExternalStorageDirectory();
			File file = new File(SDCardRoot,name);
			FileOutputStream fileOutput = new FileOutputStream(file);
			InputStream inputStream = urlConnection.getInputStream();
			int totalSize = urlConnection.getContentLength();
			int downloadedSize = 0;
			byte[] buffer = new byte[1024];
			int bufferLength = 0; //used to store a temporary size of the buffer
			while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				//Log.i(MODULE,"Downloading");
			}
			fileOutput.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void handleDebugClick(View v){
		//Log.i(MODULE, "Debug yo");
		new TestWebserver().execute();
	}
	/*
	 * 
    PRIVATE CLASSES
	 *
	 */
	private class  GatherUserInfo extends AsyncTask{

		private Bundle getUserInfo(){ // POSSO VERIFICAR PRIMEIRO SE JA EXISTE NAS SP
			try {
				//Log.i(MODULE, " no dropbox linked.. getting user info");
				Message msg = new Message();
				Account usr;
				usr = mDBApi.accountInfo();
				//Log.i("Test Gather Info", usr.displayName+" "+usr.country+" "+usr.uid);
				msg.arg1=1;
				Bundle b = new Bundle();
				b.putString(USER_KEY,usr.displayName);
				b.putString(USER_ID_KEY,usr.uid+"");
				msg.setData(b);
				gui_handler.sendMessage(msg);
				return b;
			} catch (DropboxException e) {
				e.printStackTrace();
				return null;
			}
		}
		//	@SuppressLint("CommitPrefEdits")
		private void flagAsInserted(){
			SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
			Editor edit = prefs.edit();
			edit.putBoolean(INSERTED_KEY, true);
			edit.commit();
			//Log.i(MODULE, "flagged");
		}
		@Override
		protected Object doInBackground(Object... arg0) {
			Bundle b = getUserInfo();	// get user info from dropbox.
			if(b!=null){
				String name =b.getString(USER_KEY);
				String id = b.getString(USER_ID_KEY);
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(USER_KEY, name));
				params.add(new BasicNameValuePair(USER_ID_KEY, id));
				//params.add(new BasicNameValuePair(EMAIL_KEY, email));

				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost("http://aveiro.m-iti.org/touchCloudProxy/insert_user.php");
				try {
					httpPost.setEntity(new UrlEncodedFormEntity(params));
					HttpResponse httpResponse = httpClient.execute(httpPost);
					HttpEntity httpEntity = httpResponse.getEntity();
					InputStream is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					JSONObject result = new JSONObject(sb.toString());
					int isInserted = result.getInt("success");
					if(isInserted==1 || isInserted==2) // inserted or already exists in the server
						flagAsInserted();
				}
				catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
			return null;	
		}
	}

	// @SuppressLint("HandlerLeak")
	private class GUI_Handler extends Handler{
		@Override
		public void handleMessage(Message msg)
		{
			switch(msg.arg1){
			case 1:
				storeUserInfo(msg.getData().getString(USER_KEY),msg.getData().getString(USER_ID_KEY),"");
				break;
			default:
				break;
			}
		}
	}
	private class  TestWebserver extends AsyncTask{

		private void testTag(){
			String link = "https://www.dropbox.com/s/6f0nlrpj14zl3ds/ic_launcher.png";
			SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
			int uid = Integer.parseInt(prefs.getString(USER_ID_KEY, "1"));
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("furl",link));
			params.add(new BasicNameValuePair("uid",""+uid));
			params.add(new BasicNameValuePair("tp","private"));
			
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost("http://aveiro.m-iti.org/touchcloud/tag.py");
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params));
				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				InputStream is = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is, "utf-8"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				String test = sb.toString();
				//Log.i(MODULE, "->"+test);
				
			}
			catch (IOException e) {
				e.printStackTrace();
			} 
			catch (IllegalStateException e) {
				e.printStackTrace();
			} 
		}
		private void readTag(){
			String code = "00f993e310bbebe4cd1e4404efc58644";
			SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
			int uid = Integer.parseInt(prefs.getString(USER_ID_KEY, "1"));
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("tcode",code));
			params.add(new BasicNameValuePair("uid",""+uid));
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost("http://aveiro.m-iti.org/touchcloud/read.py");
			//Log.i(MODULE, httpPost.getURI().toString());
			//Log.i(MODULE,uid+"");

			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params));
				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				InputStream is = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is, "utf-8"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				String test = sb.toString();
				//Log.i(MODULE, "->"+test);
				
			}
			catch (IOException e) {
				e.printStackTrace();
			} 
			catch (IllegalStateException e) {
				e.printStackTrace();
			} 
		}
		protected Object doInBackground(Object... arg0) {
			readTag();
			return null;	
		}
	}
}
//private class GenerateShareLink extends AsyncTask<String, Long, Boolean> {
//	@Override
//	protected Boolean doInBackground(String... path) {
//		testGatherLink(path[0]);
//		return null;
//	}
//}
//private class GotoDropBox extends AsyncTask<Void, Void, Void>{
//
//	@Override
//	protected Void doInBackground(Void... arg0) {
//		Uri uri = Uri.parse("http://db.tt/M1WLiiOm");
//		Intent i = new Intent(Intent.ACTION_VIEW, uri);
//		startActivityForResult(i,1);
//		return null;
//	}
//
//}
//private class  TestGatherinfo extends AsyncTask{
//
//	private Bundle getUserInfo(){ // POSSO VERIFICAR PRIMEIRO SE JA EXISTE NAS SP
//		try {
//			//Log.i(MODULE, " no dropbox linked.. getting user info");
//			Message msg = new Message();
//			Account usr;
//			usr = mDBApi.accountInfo();
//			//Log.i("Test Gather Info", usr.displayName+" "+usr.country+" "+usr.uid);
//			msg.arg1=1;
//			Bundle b = new Bundle();
//			b.putString(USER_KEY,usr.displayName);
//			b.putString(USER_ID_KEY,usr.uid+"");
//			msg.setData(b);
//			gui_handler.sendMessage(msg);
//			return b;
//		} catch (DropboxException e) {
//			e.printStackTrace();
//			return null;
//		}
//	}
//	//	@SuppressLint("CommitPrefEdits")
//	private void flagAsInserted(){
//		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
//		Editor edit = prefs.edit();
//		edit.putBoolean(INSERTED_KEY, true);
//		edit.commit();
//		//Log.i(MODULE, "flagged");
//	}
//	@Override
//	protected Object doInBackground(Object... arg0) {
//		Bundle b = getUserInfo();	// get user info from dropbox.
//		if(b!=null){
//			String name =b.getString(USER_KEY);
//			String id = b.getString(USER_ID_KEY);
//			// Building Parameters
//			List<NameValuePair> params = new ArrayList<NameValuePair>();
//			params.add(new BasicNameValuePair(USER_KEY, name));
//			params.add(new BasicNameValuePair(USER_ID_KEY, id));
//			//params.add(new BasicNameValuePair(EMAIL_KEY, email));
//
//			DefaultHttpClient httpClient = new DefaultHttpClient();
//			HttpPost httpPost = new HttpPost("http://aveiro.m-iti.org/touchCloudProxy/insert_user.php");
//			try {
//				httpPost.setEntity(new UrlEncodedFormEntity(params));
//				HttpResponse httpResponse = httpClient.execute(httpPost);
//				HttpEntity httpEntity = httpResponse.getEntity();
//				InputStream is = httpEntity.getContent();
//				BufferedReader reader = new BufferedReader(new InputStreamReader(
//						is, "iso-8859-1"), 8);
//				StringBuilder sb = new StringBuilder();
//				String line = null;
//				while ((line = reader.readLine()) != null) {
//					sb.append(line + "\n");
//				}
//				is.close();
//				JSONObject result = new JSONObject(sb.toString());
//				int isInserted = result.getInt("success");
//				if(isInserted==1 || isInserted==2) // inserted or already exists in the server
//					flagAsInserted();
//			}
//			catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} 
//			catch (IllegalStateException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (JSONException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} 
//		}
//		return null;	
//	}
//}
//private void testOpenPath(){
//	Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//	Uri uri = Uri.parse("/aula/teste 2/");
//	String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl("/aula/teste 2/");
//	extension = extension.toLowerCase();
//	intent.setDataAndType(uri, extension);
//	startActivity(Intent.createChooser(intent, "Open folder"));
//}
//private String[] checkFileNameSimple(String db_link){
//	String[] result = new String[2];
//	String[] tag_tokens = URLDecoder.decode(db_link).split("/");
//	String filename = tag_tokens[tag_tokens.length-1];
//	result[0] = filename;
//	result[1] = db_link;
//	return result;
//}
//private boolean isFolder(String filename){
//	return !filename.contains(".");
//}
//@Override
//public boolean onOptionsItemSelected (MenuItem item){
//	switch (item.getItemId()){
//	case R.id.debug_fucn:
//		//Log.d(MODULE, "reday to debug yo");
//		//buildDownloadLink("https://www.dropbox.com/s/niwtllwc2c0180m/classifica%C3%A7%C3%A3o.docx");
//		new InsertTest().execute();
//		//testSlashPath("/Android/data/com.dropbox.android/files/scratch/file.png");
//		break;
//	}
//	return true;
//}
//private void testSlashPath(String path){
//	String path_slashed = path.substring(0,path.lastIndexOf('/')+1);
//	//Log.i(MODULE, path_slashed);
//}
//private void doAddFileDummy(){
//	File file = new File(Environment.getExternalStorageDirectory() + "/sa.jpg");
//	FileInputStream inputStream;
//	try {
//		inputStream = new FileInputStream(file);
//		Entry response;
//		response = mDBApi.putFile("/sa.jpg", inputStream,
//				file.length(), null, null);
//		//Log.i("DbExample//Log", "The uploaded file's rev is: " + response.rev);
//
//	} catch (DropboxException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//	catch (FileNotFoundException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//}
//private void isertUserInfo(String info){
//((TextView)findViewById(R.id.user_id_info)).setText(info);
//}
//public void handleUploadClick(View v){
//GenerateShareLink test = new GenerateShareLink();
//test.execute();
//}
//public void handleOpenDropboxClick(View v){
//GotoDropBox test = new GotoDropBox();
//test.execute();
//}
//public void handleGetUserInfo(View v){
//TestGatherinfo test = new TestGatherinfo();
//test.execute();
//}
//public void handleSelectClick(View v){
//Intent i = new Intent(getApplicationContext(),SelectFileAct.class);
//startActivityForResult(i,1);
//}